package com.ncui.wisdomLearn.biz.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ncui.wisdomLearn.api.entity.LoginLog;
import com.ncui.wisdomLearn.biz.user.mapper.LoginLogMapper;
import com.ncui.wisdomLearn.biz.user.service.LoginLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 登录日志表(LoginLog)表 服务实现类
 *
 * @author lvlele
 * @since 2025-01-07 15:12:13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {

    @Override
    public boolean recordLogin(Long userId, String loginIp) {
        LoginLog loginLog = LoginLog.builder()
                .userId(userId)
                .loginIp(loginIp)
                .loginTime(new Date())
                .build();

        return save(loginLog);
    }

    @Override
    public boolean recordLogout(Long userId) {
        // 获取最近一条未登出的记录
        LambdaQueryWrapper<LoginLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LoginLog::getUserId, userId)
                .isNull(LoginLog::getLogoutTime)
                .orderByDesc(LoginLog::getLoginTime)
                .last("LIMIT 1");

        LoginLog loginLog = getOne(wrapper);
        if (loginLog != null) {
            loginLog.setLogoutTime(new Date());
            return updateById(loginLog);
        }
        return false;
    }

    @Override
    public LoginLog getLastLoginRecord(Long userId) {
        LambdaQueryWrapper<LoginLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LoginLog::getUserId, userId)
                .orderByDesc(LoginLog::getLoginTime)
                .last("LIMIT 1");
        return getOne(wrapper);
    }
}

